<template>
  <!-- 地区销量折线趋势图组件 -->
  <div class="com-container">
    <div class="title"
      :style="{fontSize:titleFontSize+'px',color:theme==='chalk'?'#fff':'#000'}">
      <span>{{'▎'+trendTitle}}</span>
      <span class="iconfont icon-arrow-down" v-if="trendTitle!==''"
        @click="showChoice=!showChoice"></span>
      <div class="select-con" :class="{active:showChoice}">
        <div class="select-item" v-for="item of trendTypeArr" :key="item.key"
          @click="selectType(item)">
          <span style="opacity:0;">h</span>{{item.text}}
        </div>
      </div>
    </div>
    <div class="com-chart" ref="trend">
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      // echarts对象
      myChart: null,
      // 数据
      trendData: {},
      // 趋势类型数组
      trendTypeArr: [],
      // 点击下拉箭头显示可选项
      showChoice: false,
      // 趋势类型
      trendType: '',
      // 趋势标题
      trendTitle: '',
      // 标题文字大小
      titleFontSize: 0
    }
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme() {
      this.myChart.dispose()
      this.initChart()
      this.updateChart()
      this.screenAdapter()
    }
  },
  created() {
    // 注册回调函数
    this.$socket.registerCallback('trendData', this.getData)
  },
  mounted() {
    this.initChart()
    // this.getData()
    // 发送数据给服务器，告诉服务器，我现在需要数据
    // 此对象的send方法在定义时已经加上JSON.stringify的转换，因此这里不用JSON.stringify
    this.$socket.send({
      action: 'getData',
      socketType: 'trendData',
      chartName: 'trend',
      value: ''
    })
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  destroyed() {
    window.removeEventListener('resize', this.screenAdapter)
    // 注销回调函数
    this.$socket.unRegisterCallback('trendData')
  },
  methods: {
    // 初始化echarts对象
    initChart() {
      this.myChart = this.$echarts.init(this.$refs.trend, this.theme)
      const initOption = {
        grid: {
          left: '5%',
          top: '30%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          left: 50,
          top: '20%',
          icon: 'circle'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            show: true,
            margin: 20
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            show: true,
            margin: 20
          }
        }
      }
      this.myChart.setOption(initOption)
    },
    // 获取数据
    getData(res) {
      // this.trendData = await this.$getApi.getTrend()
      this.trendData = res
      this.trendType = this.trendData.type[0].key
      this.trendTitle = this.trendData.type[0].text
      // 筛选掉当前显示的趋势类型，避免下拉可选项与当前标题重复
      this.trendTypeArr = this.trendData.type.filter(
        item => item.key !== this.trendType
      )
      this.updateChart()
    },
    // 更新图表
    updateChart() {
      // 半透明的颜色值
      const colorArr1 = [
        'rgba(11, 168, 44, 0.5)',
        'rgba(44, 110, 255, 0.5)',
        'rgba(22, 242, 217, 0.5)',
        'rgba(254, 33, 30, 0.5)',
        'rgba(250, 105, 0, 0.5)'
      ]
      // 全透明的颜色值
      const colorArr2 = [
        'rgba(11, 168, 44, 0)',
        'rgba(44, 110, 255, 0)',
        'rgba(22, 242, 217, 0)',
        'rgba(254, 33, 30, 0)',
        'rgba(250, 105, 0, 0)'
      ]
      // 类目轴数据
      const monthArr = this.trendData.common.month
      const valueArr = this.trendData[this.trendType].data
      // 每个系列数值轴数据的数组
      const seriesArr = valueArr.map((item, index) => {
        return {
          // 折线图
          type: 'line',
          name: item.name,
          data: item.data,
          // 最大值、最小值
          markPoint: {
            data: [{ type: 'min' }, { type: 'max' }]
          },
          // 平均线
          markLine: {
            data: [{ type: 'average' }]
          },
          areaStyle: {
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: colorArr1[index] },
              { offset: 1, color: colorArr2[index] }
            ])
          }
        }
      })
      const legendArr = valueArr.map(item => item.name)
      const dataOption = {
        xAxis: {
          data: monthArr
        },
        legend: {
          data: legendArr,
          selectedMode: 'single'
        },
        series: seriesArr
      }
      this.myChart.setOption(dataOption)
    },
    // 图表适配浏览器窗口大小变化
    screenAdapter() {
      this.titleFontSize = (this.$refs.trend.offsetWidth / 100) * 3.6
      const adaptOption = {
        legend: {
          // （圆形）图例宽度
          itemWidth: this.titleFontSize / 1.5,
          // （圆形）图例高度
          itemHeight: this.titleFontSize / 1.5,
          // （圆形）图例间距
          itemGap: this.titleFontSize / 1.5,
          textStyle: {
            fontSize: this.titleFontSize / 1.5
          }
        },
        xAxis: {
          axisLabel: {
            textStyle: {
              fontSize: this.titleFontSize / 2
            }
          }
        },
        yAxis: {
          axisLabel: {
            textStyle: {
              fontSize: this.titleFontSize / 2
            }
          }
        }
      }
      this.myChart.setOption(adaptOption)
      this.myChart.resize()
    },
    // 点击不同的趋势类型，更新图表
    selectType(item) {
      this.trendType = item.key
      this.trendTitle = item.text
      this.trendTypeArr = this.trendData.type.filter(
        item => item.key !== this.trendType
      )
      this.updateChart()
    }
  }
}
</script>

<style lang="less" scoped>
.com-container {
  position: relative;
  .title {
    position: absolute;
    left: 20px;
    top: 20px;
    z-index: 1;
    font-weight: 800;
    .select-con {
      opacity: 0;
      pointer-events: none;
      transition: opacity 0.2s;
      &.active {
        opacity: 1;
        pointer-events: auto;
      }
      .select-item {
        cursor: pointer;
      }
    }
    .icon-arrow-down {
      margin-left: 10px;
      font-size: 1em;
      cursor: pointer;
    }
  }
}
</style>
